import logging
import datetime
from logging import FileHandler
from flask import Flask, jsonify, request
from flask_cors import CORS
from views.firstbp import firstbp
from views.userbp import userbp
from uitils.jwton import jwte
from uitils.redison import red

from config import Config
from db import db1

def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app
app = create_app()

app.config.from_object(Config)

CORS(app)
app.register_blueprint(firstbp)
app.register_blueprint(userbp)


@app.route('/test')
async def hello_world():
    str = '请求ip:'+request.remote_addr+',请求的url'+request.url+',错误信息'+'\n'
    app.logger.error(str)
    res = '牛逼'
    return jsonify({'code':200,'list':res})


# 每一个请求前判断token及去权限
# @app.before_request
def beforerequest():
    white = ['/login']
    if request.path not in white:
        try:
            # 从头部获取token
            token = request.headers['Token']
        except:
            # token解析认证,token有问题直接返回
            return jsonify({'code': 10100, 'msg': '无权限'})
        if jwte.jwt_check(token) == False:
            return jsonify({'code': 10500, 'msg': 'token不正常'})
        # 权限认证,id 从哪来,从token中解析uid
        payload = jwte.jwt_de(token)
        uid = payload['data']['uid']
        key = 'interfacelists'+str(uid)
        # 根据健名+uid,去redis中获取 url 列表
        list = red.set_get_set(key)
        # 获取当前url request.path redis 获取此人拥有的权限
        if request.path not in list:
            print(111)
            return jsonify({'code':10200,'msg':'无权访问'})









if __name__ == '__main__':
    filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m')
    handler = logging.FileHandler("logs/"+filename+'.txt',encoding='utf8')
    app.logger.addHandler(handler)
    app.run()
